import React, { Component } from 'react';
import styles from './index.less';
import { Icon, Tag, Upload, message } from 'antd';
import defaultProductPic from '@/assets/imgs/productDefault.png';
import _ from 'lodash';
import Ellipsis from '@/components/Ellipsis';
import MyIcon from '@/components/MyIcon';
import { connect } from 'dva';

@connect()
class ProductPic extends Component {
  state = {
    fileUploading: false,
    fileList: [],
    imageUrl: '',
    brandClass: {
      环球通: 'huanqiutong',
      智舱宝: 'zhicangbao',
      如意鲜: 'ruyixian',
      包达天下: 'baodatianxia',
      如翼达: 'ruyida',
    },
  };

  static validate(rule, value, callback) {
    if (_.isEmpty(value)) {
      callback(rule.message);
    }
    callback();
  }
  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  beforeUpload = file => {
    if (!/\/(jpg|jpeg|png)$/.test(file.type)) {
      message.error('文件格式不正确', 10);
      return false;
    }
    const imgType = ['jpg', 'jpeg', 'png'];
    const fileType = file.type.split('/')[1];
    const isImg = imgType.includes(fileType);
    let maxSize = isImg ? 2 : 10;
    const scaleOut = file.size / 1024 / 1024 <= maxSize;
    if (!scaleOut) {
      message.error(`上传文件必须小于${maxSize}MB!`, 10);
      return false;
    }
    return scaleOut;
  };
  handleChange = info => {
    const { onChange } = this.props;
    if ('uploading' === info.file.status) {
      this.setState({ fileUploading: true });
      return;
    }
    if ('done' === info.file.status) {
      if (info.file.response.errorCode === 0) {
        onChange(info.file.response.data);
        this.getBase64(info.file.originFileObj, imageUrl => {
          this.setState({
            imageUrl,
            fileUploading: false,
            fileList: [info.file.response.data],
          });
        });
      } else {
        this.setState({ fileUploading: false });
        message.error(info.file.response.msg, 10);
      }
    }
  };
  render() {
    const {
      isUpload = false,
      showResult = true,
      info = { imageFile: {} },
      value,
      productDefaultPic = [],
    } = this.props;
    const { fileList, imageUrl, brandClass } = this.state;
    const picPath = value ? value.path : '' || info.imageFile.path || imageUrl;
    const brandName = info.brandName ? info.brandName : info.tagNameList ? info.tagNameList[0] : '';
    const brandClassName = `iconcmn---${brandClass[brandName]}`;
    const defaultPic =
      brandName && productDefaultPic.length !== 0
        ? productDefaultPic.filter(item => item.name === brandName).length !== 0
          ? productDefaultPic.filter(item => item.name === brandName)[0].image
          : defaultProductPic
        : defaultProductPic;
    return (
      <div className={styles.productPicBox}>
        {isUpload ? (
          <Upload
            showUploadList={false}
            action="/api/v1/sys/files/upload"
            accept=".JPEG,.JPG,.PNG"
            beforeUpload={this.beforeUpload}
            onChange={this.handleChange}
          >
            {!picPath ? (
              <div className={styles.uploadContainer}>
                <div className={styles.uploadPicBox}>
                  <Icon type="plus-circle" style={{ fontSize: '45px', marginTop: 30 }} />
                  <span className={styles.uploadTip}>上传图片</span>
                  <span className={styles.formatTip}>格式：JPG/PNG</span>
                  <span className={styles.formatTip}>可拖拽上传</span>
                </div>
              </div>
            ) : (
              <img className={styles.picBox} src={picPath} alt="产品主图" />
            )}
          </Upload>
        ) : (
          <div className={styles.uploadContainer}>
            <img className={styles.picBox} src={picPath} alt="产品主图" />
          </div>
        )}
        {showResult && (
          <div className={styles.picContainer}>
            <div className={styles.picTitle}>展示效果:</div>
            <div className={styles.picBox}>
              {picPath ? (
                <img className={styles.pic} src={picPath} alt="产品主图" />
              ) : (
                <img className={styles.pic} src={defaultPic} alt="默认主图" />
              )}
            </div>
            <div className={styles.infoBox}>
              <span className={styles.name}>
                <Ellipsis tooltip length={13}>
                  {info.name || '产品名称在这里'}
                </Ellipsis>
              </span>
              <span className={styles.info}>
                <Ellipsis tooltip length={15}>
                  {info.introduction || '产品介绍在这里展示不超过15个字'}
                </Ellipsis>
              </span>
              <div className={styles.bottomInfo}>
                <div className={styles.tagBox}>
                  {info.tagNameList &&
                    info.tagNameList.length > 0 &&
                    info.tagNameList.filter((tag, index) => index !== 0).map(tag => {
                      return <Tag color="volcano">{tag}</Tag>;
                    })}
                  {(!info.tagNameList || info.tagNameList.length <= 1) &&
                    isUpload && (
                      <>
                        <Tag color="volcano">标签一</Tag>
                        <Tag color="volcano">标签二</Tag>
                      </>
                    )}
                </div>
                {brandName ? (
                  <MyIcon type={brandClassName} style={{ fontSize: '30px' }} />
                ) : (
                  <div className={styles.product} />
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }
}

export default ProductPic;
